import React, { useState, useRef } from 'react';
import { Upload, X, File, CheckCircle, AlertCircle, CloudUpload } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Progress } from '@/components/ui/progress';
import { http } from '@/utils/http';
import { buildApiUrl } from '@/config/api';

const FileUploadDialog = ({ open, onOpenChange, sourceId, currentPath, onUploadComplete }) => {
  const [dragActive, setDragActive] = useState(false);
  const [uploadFiles, setUploadFiles] = useState([]);
  const fileInputRef = useRef(null);

  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFiles(e.dataTransfer.files);
    }
  };

  const handleFileInputChange = (e) => {
    if (e.target.files && e.target.files[0]) {
      handleFiles(e.target.files);
    }
  };

  const handleFiles = (fileList) => {
    const newFiles = Array.from(fileList).map((file, index) => ({
      id: Date.now() + index,
      file,
      name: file.name,
      size: formatFileSize(file.size),
      progress: 0,
      status: 'pending'
    }));
    
    setUploadFiles(prev => [...prev, ...newFiles]);
    
    newFiles.forEach(fileItem => {
      uploadFile(fileItem);
    });
  };

  const uploadFile = async (fileItem) => {
    try {
      setUploadFiles(prev => prev.map(f => 
        f.id === fileItem.id ? { ...f, status: 'uploading' } : f
      ));

      const formData = new FormData();
      formData.append('files', fileItem.file);

      const uploadPathBase64 = btoa(encodeURIComponent(currentPath || '/'));

      const xhr = new XMLHttpRequest();

      xhr.upload.addEventListener('progress', (e) => {
        if (e.lengthComputable) {
          const progress = Math.round((e.loaded / e.total) * 100);
          setUploadFiles(prev => prev.map(f => 
            f.id === fileItem.id ? { ...f, progress } : f
          ));
        }
      });

      xhr.addEventListener('load', () => {
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText);
            if (response.code === "200" && response.msg === "success") {
              setUploadFiles(prev => prev.map(f => 
                f.id === fileItem.id ? { ...f, status: 'completed', progress: 100 } : f
              ));
              if (onUploadComplete) {
                onUploadComplete();
              }
            } else {
              throw new Error(response.msg || '上传失败');
            }
          } catch (error) {
            setUploadFiles(prev => prev.map(f => 
              f.id === fileItem.id ? { ...f, status: 'error', error: error.message } : f
            ));
          }
        } else {
          setUploadFiles(prev => prev.map(f => 
            f.id === fileItem.id ? { ...f, status: 'error', error: '上传失败' } : f
          ));
        }
      });

      xhr.addEventListener('error', () => {
        setUploadFiles(prev => prev.map(f => 
          f.id === fileItem.id ? { ...f, status: 'error', error: '网络错误' } : f
        ));
      });

      const token = localStorage.getItem('authToken') || sessionStorage.getItem('authToken');
      
      xhr.open('POST', buildApiUrl(`/storage/stg-file/upload?sourceId=${sourceId}&uploadPathBase64=${uploadPathBase64}`));
      if (token) {
        xhr.setRequestHeader('Authorization', `Bearer ${token}`);
      }
      xhr.send(formData);

    } catch (error) {
      setUploadFiles(prev => prev.map(f => 
        f.id === fileItem.id ? { ...f, status: 'error', error: error.message } : f
      ));
    }
  };

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const removeUploadFile = (fileId) => {
    setUploadFiles(prev => prev.filter(f => f.id !== fileId));
  };

  const retryUpload = (fileId) => {
    const fileItem = uploadFiles.find(f => f.id === fileId);
    if (fileItem) {
      setUploadFiles(prev => prev.map(f => 
        f.id === fileId ? { ...f, status: 'pending', progress: 0, error: null } : f
      ));
      uploadFile(fileItem);
    }
  };

  const clearCompletedUploads = () => {
    setUploadFiles(prev => prev.filter(f => f.status !== 'completed'));
  };

  const getUploadStatusIcon = (status) => {
    switch (status) {
      case 'completed':
        return <CheckCircle className="w-4 h-4 text-green-600" />;
      case 'error':
        return <AlertCircle className="w-4 h-4 text-red-600" />;
      default:
        return <Upload className="w-4 h-4 text-blue-600" />;
    }
  };

  const handleClose = () => {
    setUploadFiles([]);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-2xl max-h-[80vh] overflow-hidden">
        <DialogHeader>
          <DialogTitle className="flex items-center justify-between">
            <span>上传文件</span>
            {uploadFiles.filter(f => f.status === 'completed').length > 0 && (
              <Button onClick={clearCompletedUploads} variant="outline" size="sm">
                清除已完成
              </Button>
            )}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6">
          <div
            className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
              dragActive
                ? 'border-primary bg-primary/5'
                : 'border-material-grey-300 hover:border-primary/50'
            }`}
            onDragEnter={handleDrag}
            onDragLeave={handleDrag}
            onDragOver={handleDrag}
            onDrop={handleDrop}
          >
            <div className="w-12 h-12 mx-auto mb-4 bg-primary/10 rounded-full flex items-center justify-center">
              <CloudUpload className="w-6 h-6 text-primary" />
            </div>
            
            <h4 className="text-lg font-medium text-material-grey-800 mb-2">
              拖拽文件到此处上传
            </h4>
            
            <p className="text-material-grey-600 mb-4">
              或者点击下方按钮选择文件
            </p>
            
            <Button
              onClick={() => fileInputRef.current?.click()}
              className="bg-primary hover:bg-primary-600"
            >
              选择文件
            </Button>
            
            <input
              ref={fileInputRef}
              type="file"
              multiple
              className="hidden"
              onChange={handleFileInputChange}
            />
            
            <p className="text-xs text-material-grey-500 mt-4">
              支持多文件上传
            </p>
            
            {currentPath && currentPath !== '/' && (
              <p className="text-xs text-blue-600 mt-2">
                上传到：{currentPath}
              </p>
            )}
          </div>

          {uploadFiles.length > 0 && (
            <div>
              <h4 className="text-sm font-medium text-material-grey-700 mb-3">
                上传队列 ({uploadFiles.length} 个文件)
              </h4>
              <div className="space-y-3 max-h-60 overflow-y-auto">
                {uploadFiles.map((file) => (
                  <div key={file.id} className="flex items-center space-x-3 p-3 bg-material-grey-50 rounded-lg">
                    <div className="flex-shrink-0">
                      {getUploadStatusIcon(file.status)}
                    </div>
                    
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between mb-1">
                        <p className="text-sm font-medium text-material-grey-800 truncate">
                          {file.name}
                        </p>
                        <span className="text-xs text-material-grey-500">
                          {file.size}
                        </span>
                      </div>
                      
                      {file.status === 'uploading' && (
                        <Progress value={file.progress} className="h-2 mb-1" />
                      )}
                      
                      <div className="flex items-center justify-between">
                        <span className="text-xs text-material-grey-600">
                          {file.status === 'pending' && '等待上传'}
                          {file.status === 'uploading' && `上传中 ${file.progress}%`}
                          {file.status === 'completed' && '上传完成'}
                          {file.status === 'error' && (file.error || '上传失败')}
                        </span>
                        
                        <div className="flex items-center space-x-2">
                          {file.status === 'error' && (
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={() => retryUpload(file.id)}
                              className="text-blue-600 hover:text-blue-700 h-6 px-2"
                            >
                              重试
                            </Button>
                          )}
                          
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => removeUploadFile(file.id)}
                            className="text-red-600 hover:text-red-700 h-6 px-2"
                          >
                            <X className="w-3 h-3" />
                          </Button>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default FileUploadDialog;
